import plugin from '../../lib/plugins/plugin.js'
import fetch from 'node-fetch'
import fs from 'node:fs'
import { segment } from 'oicq'
import yaml from "yaml"

/*
* 图片来源
* https://iw233.cn
* https://app.zichen.zone/api/acg.php?json=1
* https://www.dmoe.cc/random.php?return=json
*/

export class xianyudaka extends plugin {
    
	constructor() {
		super({
			/** 功能名称 */
        name: '每日打卡',
        /** 功能描述 */
        dsc: '打卡，随机发一张二次元图',
        /** https://oicqjs.github.io/oicq/#events */
        event: 'message',
        /** 优先级，数字越小等级越高 */
        priority: 5500,
        rule: [
          {
            /** 命令正则匹配 */
            reg: '^打卡$',
            /** 执行方法 */
            fnc: 'dk',
          },
          {
            /** 命令正则匹配 */
            reg: '^壁纸$',
            /** 执行方法 */
            fnc: 'bizhi',
          },
          {
            /** 命令正则匹配 */
            reg: '^#?图?转链接', //这个是图片转链接的，发#图转链接+一张图，得到链接
            /** 执行方法 */
            fnc: 'lianjie',
          },
        ]
    })
  }

  async lianjie(e) {
    if(e.img) {
      e.reply(e.img[0]);
      return true;
    }
    e.reply('请和图片一起发送')
    return true;
  }

  async dk(e) {
    //检查文件是否存在，不存在则创建
    fs.access(`${process.cwd()}/data/daka.yaml`, fs.constants.F_OK, (err) => {
      if(err){
          let notes = [{
              "user":"用户qq",
              "name":"昵称",
              "day":"打卡日期",
              "time":"当天的打卡时间",
              "paw":"获取壁纸次数",
          }]
          let yamlstr = yaml.stringify(notes);//json转yaml
          fs.writeFile(File,yamlstr,function (err){
              if (err) throw err;
              console.log('daka.yaml文件创建成功');
          })
      }
    });

    let yam = fs.readFileSync(`${process.cwd()}/data/daka.yaml`,'utf8'); //打开文件
    let obj = yaml.parse(yam);//yaml转json

    let date = new Date(),
    month = date.getMonth() + 1,
    day1 = date.getDate(),
    hour = date.getHours(),
    minute = date.getMinutes(),
    second = date.getSeconds();

    let day = `${month}-${day1}`; //打卡日期
    let time = `${hour}:${minute}:${second}`; //打卡时间

    console.log(day+'\n'+time)

    let daka;
    for(const i in obj) {
      if(obj[i].user === e.user_id) {
        daka = i;
      }
    }

    if(daka) {
      if(obj[daka].day === day) {
        //这吊毛已经打过卡了
        e.reply(`今日已打卡\n${obj[daka].time}`)
        return true;
      }
      //刷新时间
      obj[daka].day = day;
      obj[daka].time = time;
      obj[daka].paw = 0;
    } else {
      //创建数据
      let data = {
        "user":e.user_id,
        "name":e.nickname,
        "day":day,
        "time":time,
        "paw":0
      }
      obj.push(data);
    }

    //写入文件
    let yamlstr = yaml.stringify(obj);//json转yaml
    fs.writeFileSync(`${process.cwd()}/data/xianyu/daka.yaml`, yamlstr, 'utf8');

    /**发送消息 */

     /* 备用接口https://app.zichen.zone/api/acg.php?json=1 */
    let url = 'https://iw233.cn/api.php?sort=random&type=json';
    let url1 = 'https://www.dmoe.cc/random.php?return=json'; //备用
    let img;
    try {
      img = await fetch(url);
      img = await img.json();
      e.reply([
        segment.at(e.user_id),
        ` 打卡成功\n`,
        segment.image(img.pic[0])
      ])
      return true;
    } catch (err) {
      img = await fetch(url1); //使用备用接口
      img = await img.json();
      e.reply([
        segment.at(e.user_id),
        ` 打卡成功\n`,
        segment.image(img.imgurl)
      ])
      return true;
    }
  }

  async bizhi(e) {
    //检查文件是否存在，不存在则创建
    fs.access(`${process.cwd()}/data/daka.yaml`, fs.constants.F_OK, (err) => {
      if(err){
          let notes = [{
              "user":"用户qq",
              "name":"昵称",
              "day":"打卡日期",
              "time":"当天的打卡时间",
              "paw":"获取壁纸次数",
          }]
          let yamlstr = yaml.stringify(notes);//json转yaml
          fs.writeFile(File,yamlstr,function (err){
              if (err) throw err;
              console.log('daka.yaml文件创建成功');
          })
      }
    });
    
    let yam = fs.readFileSync(`${process.cwd()}/data/daka.yaml`,'utf8'); //打开文件
    let txt = yaml.parse(yam);//yaml转json

    let bizhi;
    for(const key in txt) {
      if(txt[key].user == e.user_id) {
        bizhi = key;
      }
    }
    if(!bizhi)  {
      e.reply(`请先打卡`)
      return true;
    }
    if(txt[bizhi].paw == '1')  {
      e.reply(`次数已到，明日再来`)
      return true;
    }

    //更新次数
    txt[bizhi].paw = 1;
    //写入文件
    let yamlstr = yaml.stringify(txt);//json转yaml
    fs.writeFileSync(`${process.cwd()}/data/daka.yaml`, yamlstr, 'utf8');

    /**发送消息 */
    let data_msg = [];
    if(bizhi) {
      let urls = [
        'https://iw233.cn/api.php?type=json&sort=cat&num=5',
        'https://iw233.cn/api.php?type=json&sort=mp&num=5',
        'https://iw233.cn/api.php?type=json&sort=pc&num=5',
        'https://iw233.cn/api.php?type=json&sort=yin&num=5',
        'https://iw233.cn/api.php?type=json&sort=top&num=5',
        'https://iw233.cn/api.php?type=json&sort=random&num=5'
      ]
      let rd = Math.floor(Math.random() * urls.length);
      console.log(urls.length);
      let img;
      try {
        img = await fetch(urls[rd]); //调用接口获取数据
      } catch (err) {
          e.reply('调用接口失败');
          return true;
      }
      let obj = await img.json();

      for(const i in obj.pic) {
        data_msg.push({
          message: segment.image(obj.pic[i]),
          nickname: e.nickname,
          user_id: e.user_id
        })
      }
      //创建合并转发消息
      let ForwardMsg = await e.group.makeForwardMsg(data_msg);  
      e.reply(ForwardMsg);
      return true;
    }
  }
}